import { defineStore } from "pinia";
import api from "@/api/user.js";
import { useRouter } from "vue-router";
const router = useRouter();
function getCurrentDate() {
  const today = new Date();
  const year = today.getFullYear();
  const month = String(today.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
  const day = String(today.getDate()).padStart(2, "0");

  return `${year}-${month}-${day}`;
}
// 创建并导出使用 Pinia 的 store
export const useAuthStore = defineStore("auth", {
  state: () => {
    return {
      time: null,
      timer: null,
      id: sessionStorage.getItem("id"),
      roomid: sessionStorage.getItem("roomid"),
    };
  },
  actions: {
    getnowtime() {
      // const router = useRouter();
      console.log(router);
      clearInterval(this.timer);
      api.gettime({
          pageSize: 1000,
          date: getCurrentDate(),
        })
        .then((res) => {
          console.log(res.rows.pop());

          if (res.rows.length == 0) {
            this.time = 30;
          } else {
            this.time = res.rows.pop().cumulativeplaytime;
            console.log(res.rows.pop().cumulativeplaytime);
          }
        });
        // if (this.time <= 0) {
     
        //   router.push("/end");
        //   clearInterval(this.timer);
        // }
      this.timer = setInterval(() => {
        this.time--;
        api
          .addtime({
            cumulativeplaytime: this.time,
            historicalupdaterecord: "游玩备注",
          })
          .then((res) => {
            console.log(res);
          });

        // if (this.time <= 0) {
     
        //   router.push("/end");
        //   clearInterval(this.timer);
        // }
      }, 60000);
    },
    setid(id) {
      this.id = id;
      sessionStorage.setItem("id", id);
    },
    setroomid(roomid) {
      this.roomid = roomid;
      sessionStorage.setItem("roomid", roomid);
    },
  },
});
